import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

class AvatarController {
    constructor() {
        this.scene = new THREE.Scene();
        this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
        this.mixer = null;
        this.morphTargetDictionary = {};
        this.controls = null;
        
        this.init();
        this.animate();
        this.setupWindowResize();
    }

    init() {
        // 设置渲染器
        this.renderer.setSize(window.innerWidth / 2, window.innerHeight);
        this.renderer.setClearColor(0xf0f0f0);
        document.getElementById('avatar-container').appendChild(this.renderer.domElement);

        // 调整相机位置
        this.camera.position.set(0, 7, 0.1);
        this.camera.lookAt(0, 10, 0);

        // 添加轨道控制器
        this.controls = new OrbitControls(this.camera, this.renderer.domElement);
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.05;
        this.controls.screenSpacePanning = true;
        this.controls.minDistance = 0;
        this.controls.maxDistance = 100;
        this.controls.maxPolarAngle = Math.PI / 1;
        this.controls.target.set(0, 1.6, 0);

        // 添加灯光
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
        this.scene.add(ambientLight);

        const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
        directionalLight.position.set(0, 1, 1);
        this.scene.add(directionalLight);

        // 添加背光
        const backLight = new THREE.DirectionalLight(0xffffff, 0.5);
        backLight.position.set(0, 0, -1);
        this.scene.add(backLight);

        // 加载模型
        const loader = new GLTFLoader();
        const modelUrl = '/models/avatar.glb';
        
        loader.load(modelUrl, (gltf) => {
            this.avatar = gltf.scene;
            
            // 计算模型包围盒
            const box = new THREE.Box3().setFromObject(this.avatar);
            const center = box.getCenter(new THREE.Vector3());
            const size = box.getSize(new THREE.Vector3());
            
            // 调整模型比例
            const scaleY = 3.2 / size.y;
            const scaleX = scaleY * 1.5;
            const scaleZ = scaleY * 1.5;
            
            this.avatar.scale.set(scaleX, scaleY, scaleZ);
            
            // 调整位置，使模型居中
            this.avatar.position.y = -center.y * scaleY;
            this.avatar.position.x = -center.x * scaleX;
            this.avatar.position.z = -center.z * scaleZ;
            
            this.scene.add(this.avatar);

            // 自动旋转到合适的角度
            this.avatar.rotation.y = Math.PI;

            // 检查模型是否包含动画
            if (gltf.animations && gltf.animations.length > 0) {
                console.log('Available animations:', gltf.animations.map(a => a.name));
                
                // 创建动画混合器
                this.mixer = new THREE.AnimationMixer(this.avatar);
                
                // 播放所有动画
                gltf.animations.forEach((clip) => {
                    const action = this.mixer.clipAction(clip);
                    action.play();
                });
            }

            // 获取表情映射
            if (this.avatar.getObjectByName('Wolf3D_Head')) {
                this.morphTargetDictionary = this.avatar.getObjectByName('Wolf3D_Head').morphTargetDictionary;
            }

            console.log('Avatar loaded successfully');
        }, 
        (progress) => {
            const percent = (progress.loaded / progress.total * 100).toFixed(2);
            console.log(`Loading model: ${percent}%`);
            const loadingElement = document.createElement('div');
            loadingElement.id = 'loading-progress';
            loadingElement.textContent = `加载中: ${percent}%`;
            document.getElementById('avatar-container').appendChild(loadingElement);
        },
        (error) => {
            console.error('Error loading model:', error);
        });
    }

    setupWindowResize() {
        window.addEventListener('resize', () => {
            // 更新相机
            this.camera.aspect = window.innerWidth / 2 / window.innerHeight;
            this.camera.updateProjectionMatrix();
            
            // 更新渲染器
            this.renderer.setSize(window.innerWidth / 2, window.innerHeight);
        });
    }

    animate() {
        requestAnimationFrame(() => this.animate());
        
        // 添加自动旋转
        if (this.avatar) {
            this.avatar.rotation.y += 0.005; // 调整旋转速度
        }

        // 更新控制器
        if (this.controls) {
            this.controls.update();
        }

        // 更新动画混合器
        if (this.mixer) {
            this.mixer.update(0.016);
        }
        
        this.renderer.render(this.scene, this.camera);
    }

    updateExpression(expression) {
        if (this.morphTargetDictionary && this.morphTargetDictionary[expression]) {
            this.avatar.getObjectByName('Wolf3D_Head').morphTargetInfluences[
                this.morphTargetDictionary[expression]
            ] = 1;
        }
    }

    updateViseme(viseme) {
        // 实现口型同步
        if (this.morphTargetDictionary && this.morphTargetDictionary[viseme]) {
            this.avatar.getObjectByName('Wolf3D_Head').morphTargetInfluences[
                this.morphTargetDictionary[viseme]
            ] = 1;
        }
    }

    playGesture(gesture) {
        // 实现手势动作
        if (this.mixer && this.avatar.animations) {
            const clip = this.avatar.animations.find(a => a.name === gesture);
            if (clip) {
                const action = this.mixer.clipAction(clip);
                action.play();
            }
        }
    }
}

export default AvatarController; 